package netty.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    /**
     * ChannelGroup: 一个 Channel 组，管理所有 Channel (其实是一个 Set 集合)
     * GlobalEventExecutor.INSTANCE: 单例的全局事件执行器
     */
    private static final ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 连接建立
     * 一旦建立连接，立即调用 handlerAdded
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("客户端: " + channel.remoteAddress() + " " + dateFormat.format(new Date()) + " 加入聊天~");
        channelGroup.add(channel);
        System.out.println("客户端: " + channel.remoteAddress() + " 上线");
    }

    /**
     * 断开连接
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("客户端: " + channel.remoteAddress() + " " + dateFormat.format(new Date()) + " 退出聊天");
        System.out.println("客户端: " + channel.remoteAddress() + " 下线");
        System.out.println("channelGroup size: " + channelGroup.size());
    }

    /**
     * 读取数据
     * @param ctx           the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *                      belongs to
     * @param msg           the message to handle
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel thisChannel = ctx.channel();
        channelGroup.forEach(channel -> {
            String time = dateFormat.format(new Date());
            if (channel != thisChannel) {
                channel.writeAndFlush(channel.remoteAddress() + " " + time  + " 发送消息: " + msg + "\n");
            } else {
                channel.writeAndFlush("自己 " + time  + " 发送消息: " + msg + "\n");
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
